<template>
  <view class="page-container">
    <!-- 开户许可证模块 -->
    <view class="upload-section">
      <view class="section-title">开户许可证</view>
      <view class="upload-card" @click="handleUploadLicense">
        <image v-if="licenseImage" :src="licenseImage" class="license-image" mode="aspectFit"></image>
        <view v-else class="upload-placeholder">
          <uni-icons type="plusempty" size="40" color="#999"></uni-icons>
          <text class="upload-text">上传开户许可证</text>
          <text class="format-tip">照片格式：jpg/png</text>
        </view>
      </view>
      <view class="notice-text">
        以下信息为系统自动识别，如不正确请修改
      </view>
    </view>

    <!-- 表单区域 -->
    <view class="form-container">
      <view class="form-item">
        <text class="form-label">开户名称</text>
        <input class="form-input" v-model="formData.accountName" placeholder="请输入开户名称"
          placeholder-class="placeholder" @input="clearError('accountName')" />
        <text class="error-msg" v-if="errors.accountName">{{ errors.accountName }}</text>
      </view>

      <view class="form-item">
        <text class="form-label">开户银行</text>
		<input class="form-input" v-model="formData.openingBank" placeholder="请输入开户名称"
		  placeholder-class="placeholder" @input="clearError('openingBank')" />
        <text class="error-msg" v-if="errors.openingBank">{{ errors.openingBank }}</text>
      </view>

     <!-- <view class="form-item">
        <text class="form-label">开户省市</text>
        <picker class="formData" mode="region" @change="handleRegionChange">
          <view class="picker-content">
            {{ formData.openingCity.length > 0? formData.openingCity.join('/') : '请选择开户省市区/县 >' }}
          </view>
        </picker>
        <text class="error-msg" v-if="errors.openingCity">{{ errors.openingCity }}</text>
      </view> -->

      <!-- <view class="form-item">
        <text class="form-label">开户支行</text>
        <input class="form-input" v-model="formData.openingSubBank" placeholder="请输入开户支行"
          placeholder-class="placeholder" @input="clearError('openingSubBank')" />
        <text class="error-msg" v-if="errors.openingSubBank">{{ errors.openingSubBank }}</text>
      </view> -->

      <view class="form-item">
        <text class="form-label">银行账号</text>
        <input class="form-input" v-model="formData.bankAccountNumber" placeholder="请输入银行账号"
          placeholder-class="placeholder" type="number" @input="clearError('bankAccountNumber')" />
        <text class="error-msg" v-if="errors.bankAccountNumber">{{ errors.bankAccountNumber }}</text>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-btn" @click="handleSubmit">
      <text>确认提交</text>
    </view>

    <view class="divider"></view>

   <!-- 未填写提示
    <view class="error-tips" v-if="showErrorTips">
      <view v-for="(error, index) in errorMessages" :key="index">
        {{ error }}
      </view>
    </view> -->
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useTokenStore } from '@/stores/jwt.js'
import { useuser } from "@/stores/user.js";
import { http } from '../../../config/request.js'

// 表单数据
const formData = reactive({
  accountName: '',
  openingBank: '',
  openingCity: [],
  openingSubBank: '',
  bankAccountNumber: '',
  permitImagePath: ''
})

// 错误信息
const errors = reactive({
  accountName: '',
  openingBank: '',
  openingCity: '',
  openingSubBank: '',
  bankAccountNumber: ''
})

// 图片上传
const licenseImage = ref('')

// 银行选项
const bankOptions = ref([
  '中国工商银行',
  '中国建设银行',
  '中国农业银行',
  '中国银行',
  '交通银行',
  '招商银行'
])

// 错误提示
const showErrorTips = ref(false)
const errorMessages = ref([])

// 处理银行选择
const handleBankChange = (e) => {
  const index = e.detail.value
  formData.openingBank = bankOptions.value[index]
  errors.openingBank = ''
}

// 处理地区选择 - 确保获取普通数组
const handleRegionChange = (e) => {
  formData.openingCity = e.detail.value.slice(0, 2) // 只取省和市
  formData.openingCity = formData.openingCity.map(String)
  errors.openingCity = ''
}

// 上传开户许可证
const handleUploadLicense = () => {
  uni.chooseImage({
    count: 1,
    success: async (res) => {
      licenseImage.value = res.tempFilePaths[0]
      uni.showLoading({
        title: '上传中...',
        mask: true
      })

      try {
        const uploadRes = await uni.uploadFile({
          url: 'http://localhost:9988/accountAuthentication/update',
          filePath: licenseImage.value,
          name: 'file',
          header: {
            'Authorization': useTokenStore().jwt // 使用正确的token
          },
          success: (up) => {
            console.log("上传成功", up.data)
            const aa = JSON.parse(up.data)
            if (aa.code === 20031) {
              formData.permitImagePath = aa.shuju.permitImagePath || ''
              formData.accountName = aa.shuju?.accountName || ''
              formData.openingBank = aa.shuju?.openingBank || ''
              formData.openingSubBank = aa.shuju?.openingSubBank || ''
              formData.bankAccountNumber = aa.shuju?.bankAccountNumber || ''

              uni.showToast({
                title: '上传成功',
                icon: 'success'
              })
            } else {
              uni.showToast({
                title: '上传失败，请重试',
                icon: 'none'
              })
            }
          }
        })
      } catch (err) {
        console.error('上传失败:', err)
        licenseImage.value = ''
        uni.showToast({
          title: err.message || '上传失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    fail: (err) => {
      console.error('选择图片失败:', err)
      uni.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  })
}

// 清除错误信息
const clearError = (field) => {
  errors[field] = ''
}

// 表单验证
const validateForm = () => {
  let isValid = true
  errorMessages.value = []
  if (!formData.openingBank) {
    errors.openingBank = '请选择开户行'
    errorMessages.value.push('请选择开户行')
    isValid = false
  }

  if(!formData.bankAccountNumber) {
    errors.bankAccountNumber = '请输入银行账号'
    errorMessages.value.push('请输入银行账号')
    isValid = false
  } else if (formData.bankAccountNumber.length < 16 || formData.bankAccountNumber.length > 19) {
    errors.bankAccountNumber = '请输入正确的银行账号(16-19位)'
    errorMessages.value.push('请输入正确的银行账号(16-19位)')
    isValid = false
  }

  showErrorTips.value =!isValid
  return isValid
}

// 提交表单
const handleSubmit = async () => {
	
  if (!validateForm()) {
    return
  }

  if (!licenseImage.value) {
    uni.showToast({
      title: '请上传开户许可证',
      icon: 'none'
    })
    return
  }

  try {
    // 将 openingCity 转换为字符串
    const openingCityStr = formData.openingCity.join('/')

    const submitData = {
      accountName: formData.accountName,
      openingBank: formData.openingBank,
      bankAccountNumber: formData.bankAccountNumber,
      permitImagePath: formData.permitImagePath,
      eid: useuser().user.id,
	  auditStatus: 0
    }
    console.log(submitData)
    const response = await http({
      url: 'http://localhost:9988/accountAuthentication/add',
      method: 'POST',
      data: submitData,
      header: {
        'Authorization': useTokenStore().jwt,
        'Content-Type': 'application/json'
      }
    })

    let resData = response.data
    if (typeof resData === 'string') {
      resData = JSON.parse(resData)
    }

    if (response.code === 20011) {
		//返回上一页
		wx.navigateBack({
			delta: 1 // 返回上一页，delta可以设置返回几层页面
		});
      uni.showToast({
        title: '提交成功',
        icon: 'success'
      })
    } else {
      throw new Error(resData.message || '提交失败')
    }
  } catch (err) {
    console.error('提交失败:', err)
    uni.showToast({
      title: err.message || '提交失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}
</script>

<style lang="scss">
.page-container {
  padding: 30rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.upload-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;

 .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }

 .upload-card {
    height: 300rpx;
    border: 2rpx dashed #ddd;
    border-radius: 12rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;

   .license-image {
      width: 100%;
      height: 100%;
    }

   .upload-placeholder {
      display: flex;
      flex-direction: column;
      align-items: center;

     .upload-text {
        font-size: 28rpx;
        color: #666;
        margin-top: 15rpx;
      }

     .format-tip {
        font-size: 24rpx;
        color: #999;
        margin-top: 10rpx;
      }
    }
  }

 .notice-text {
    font-size: 26rpx;
    color: #999;
    margin-top: 20rpx;
  }
}

.form-container {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;

 .form-item {
    margin-bottom: 30rpx;
    position: relative;

    &:last-child {
      margin-bottom: 0;
    }

   .form-label {
      display: block;
      font-size: 28rpx;
      color: #666;
      margin-bottom: 10rpx;
    }

   .form-input {
      height: 80rpx;
      line-height: 80rpx;
      padding: 0 20rpx;
      background-color: #f9f9f9;
      border-radius: 8rpx;
      font-size: 28rpx;
      color: #333;
    }

   .picker-content {
      height: 80rpx;
      line-height: 80rpx;
      padding: 0 20rpx;
      background-color: #f9f9f9;
      border-radius: 8rpx;
      font-size: 28rpx;
      color: #999;
    }

   .error-msg {
      position: absolute;
      bottom: -40rpx;
      left: 0;
      font-size: 24rpx;
      color: #ff4d4f;
    }
  }
}

.submit-btn {
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  background-color: #1890ff;
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
  margin: 40rpx 0;
}

.divider {
  height: 1rpx;
  background-color: #eee;
  margin: 30rpx 0;
}

.error-tips {
  font-size: 26rpx;
  color: #ff4d4f;
  padding: 20rpx;
  background-color: #fff2f0;
  border-radius: 8rpx;

  view {
    margin-bottom: 10rpx;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.placeholder {
  color: #ccc;
  font-size: 28rpx;
}
</style>